package model

import (
	"context"
	"fmt"
	"service/ctrl"
	"service/model/mod"

	gpa "gitee.com/cloudapex/protos/hr_cache/pb"
	gpb "gitee.com/cloudapex/protos/hr_cache/pb"
	"gitee.com/cloudapex/ulern/util"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
)

var FrameWorkCache frameWorkCache

func init() {
	ctrl.GCon.RegistClienter(mod.GCONN_HR_CACHE, func(c *grpc.ClientConn) { FrameWorkCache.cli = gpa.NewFrameworkCacheClient(c) })
}

type frameWorkCache struct {
	cli gpa.FrameworkCacheClient
}

//  frameWorkCache.FrameCacheList
func (this *frameWorkCache) FrameCacheList(ctx context.Context, in *gpa.FrameworkCacheReq, showId int64) (bool, error) {
	var fage bool
	rsp, err := this.cli.GetAllFrame(ctx, in)
	if s := status.Convert(err); s.Err() != nil {
		return false, s.Err()
	}

	if len(rsp.FrameMap) > 0 {
		for _, v := range rsp.FrameMap {
			if v.Id == showId {
				fage = true
			}
		}
	}
	return fage, err
}

//  frameWorkCache.GetAllFrame 获取组织架构列表
func (this *frameWorkCache) FrameCacheReqList(ctx context.Context, in *gpa.FrameworkCacheReq) (*gpa.GetFrameMap, error) {
	return this.cli.GetAllFrame(ctx, in)
}

var fName string
var issupId bool

// frameWorkCache.GetFrameName 根据员工表中fid寻找组织架构全名
func (this *frameWorkCache) GetFrameName(showId int64, cid int64, maps *gpa.GetFrameMap) string {
	util.Debug("传过来的showID%d", showId)

	if !issupId {
		fName = ""
	}

	var err error
	var name string
	res, has := maps.FrameMap[showId]
	util.Debug("取出来的缓冲值%s", res)

	if has {
		name = res.Name
		fName = name + fName
		util.Debug("缓冲里取出来的名称%s", fName)

		if res.Superior != 0 {
			fmt.Println(fName)
			issupId = true
			this.GetFrameName(res.Superior, cid, maps)
		}
	}
	issupId = false
	fmt.Println("---------", err, fName)
	util.Debug("最后取出来的名称%s", fName)

	return fName
}

// frameWorkCache.AddFramework 添加组织架构
func (this *frameWorkCache) AddFramework(ctx context.Context, in *gpa.FrameworkCacheReq) (*gpa.FrameworkCacheRes, error) {
	return this.cli.AddFramework(ctx, in)
}

// frameWorkCache.AddFramework 更新组织架构
func (this *frameWorkCache) EditFramework(ctx context.Context, in *gpb.FrameworkCacheReq) (*gpb.FrameworkCacheRes, error) {
	return this.cli.EditFramework(ctx, in)
}

func (this *frameWorkCache) GetFraNameByShowIdList(ctx context.Context, in *gpb.FullReqUIdsReq) (*gpb.FullUListRes, error) {
	return this.cli.GetFraNameByShowIdList(ctx, in)
}

//   ---------------用于首咨数据分配------------------------------
//  	说明：根据当前用户showId (多个传最小级别的（值最大）) 返回数据取值范围 showIds[]
//  	参数：1.CId     公司ID
//  	     2.[]Id    架构id
func (this *frameWorkCache) GetUserAllSeeIds(ctx context.Context, in *gpb.AllShowReq) (*gpb.AllShowRes, error) {
	return this.cli.GetUserAllSeeIds(ctx, in)
}
